import { isElementVisible } from './group-helper.js';
import { OldCardExtractor } from './card-extractors/old-card-extractor.js';
import { NewCardExtractor } from './card-extractors/new-card-extractor.js';
import { TableCardExtractor } from './card-extractors/table-card-extractor.js';
import { ListCardExtractor } from './card-extractors/list-card-extractor.js';

// 创建提取器实例
const extractors = [
  new OldCardExtractor(),
  new NewCardExtractor(),
  new TableCardExtractor(),
  new ListCardExtractor()
];

// 递归查找指标卡片
export function findCards(container, startElement = null) {
  const cards = [];
  
  // 使用所有提取器查找卡片
  extractors.forEach(extractor => {
    const cardElements = Array.from(container.querySelectorAll(extractor.getCardSelector()))
      .filter(cardElement => isElementVisible(cardElement));
      
    cardElements.forEach(cardElement => {
      // TableCardExtractor 特殊处理
      if (extractor instanceof TableCardExtractor) {
        const tableCards = extractor.extract(cardElement);
        if (Array.isArray(tableCards)) {
          cards.push(...tableCards);
        }
      } else {
        // 如果指定了起始元素，只处理在它之后的卡片
        if (startElement) {
          const cardRect = cardElement.getBoundingClientRect();
          const startRect = startElement.getBoundingClientRect();
          if (cardRect.top <= startRect.top) {
            return;
          }
        }
        
        const card = extractor.extract(cardElement);
        if (card) {
          cards.push(card);
        }
      }
    });
  });
  
  // 如果没有直接找到卡片，递归查找子容器
  if (cards.length === 0) {
    const childContainers = Array.from(container.children)
      .filter(child => isElementVisible(child));
    
    childContainers.forEach(childContainer => {
      const childCards = findCards(childContainer, startElement);
      cards.push(...childCards);
    });
  }
  
  return cards;
} 